<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="/static/js/socket.io.js"></script>
    <script src="/static/js/jquery-2.0.2.min.js"></script>
    <script src="/static/js/jquery.cookie.js"></script>
</head>

<body>
    <input type="button" value="发送消息" id="send">
    <input type="button" value="hello" id="hello">
    <input type="button" value="不存在的方法" id="wrong">
    <input type="button" value="chat/index" id="chat">
	<a target="_blank" href="/index/websocket/news">news</a>
    <script>
        //登录获取jwt
        function auth() {
            var token = $.cookie('auth');
            if (token) return token;
            $.ajaxSetup({
                async: false
            });
            $.get('/index/websocket/login', { username: 'admin', password: 'admin' }, function (data) {
                token = data.token;
            }, 'json');
            $.ajaxSetup({
                async: true
            });
            $.cookie('auth', token);
            return token;
        }

        var ws = io('ws://nc.com', { query: "token=" + auth() });
        ws.on('connect', function (e) {
            console.log("连接服务器成功");
        });
        ws.on('disconnect', function () {
            console.log("disconnect");
            clearInterval(window.ttl);
        });
        ws.on('communication', function (data) {
            console.log('get:', data);
        });
        //每隔50秒ping一次
        window.ttl = setInterval(function () {
            ws.emit('communication', { controller: 'websocket', action: 'ping' });
        }, 50000);
        document.getElementById('send').onclick = function () {
            ws.emit('communication', {
                controller: 'index',
                action: 'index',
                name: 'zhangsan',
                age: 20,
                time: new Date().getTime()
            });
        }
        document.getElementById('hello').onclick = function () {
            ws.emit('communication', {
                controller: 'index',
                action: 'hello',
                words: 'hi'
            });
        }
        document.getElementById('wrong').onclick = function () {
            ws.emit('communication', {
                controller: 'dfdfdfd',
                action: 'hello',
                words: 'hi'
            });
        }
        document.getElementById('chat').onclick = function () {
            ws.emit('communication', {
                controller: 'chat',
                action: 'index',
                words: '你是谁？'
            });
        }
    </script>
</body>

</html>